<template>
  <div class="test-container">
    <template v-if="this.templateTag === 'template'">
    <el-table :data="fields" tooltip-effect="dark" style="width: 100%" border>
      <el-table-column prop="field" label="字段名称">
        <template slot-scope="field">
          <el-input v-model="field.row.field" placeholder="字段名称" autocomplete="off" clearable />
        </template>
      </el-table-column>
      <el-table-column prop="type" label="数据类型">
        <template slot-scope="field">
          <el-select  v-model="field.row.type" filterable placeholder="请选择" prop="type">
            <el-option-group
                    v-for="group in types"
                    :key="group.label"
                    :label="group.label">
              <el-option
                      v-for="(item, key) in group.options"
                      :key="key"
                      :label="item.value"
                      :value="item.value">
              </el-option>
            </el-option-group>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="comment" label="字段注释">
        <template slot-scope="field">
          <el-input v-model="field.row.comment" placeholder="字段注释" autocomplete="off" clearable />
        </template>
      </el-table-column>
      <el-table-column prop="inputType" label="控件类型">
        <template slot-scope="field">
          <el-select  v-model="field.row.inputType" filterable placeholder="请选择" prop="inputType">
           <!-- <el-option-group
                    v-for="group in inputTypes"
                    :key="group.label"
                    :label="group.label">
              <el-option
                      v-for="(item, key) in group.options"
                      :key="key"
                      :label="item.value"
                      :value="item.value">
              </el-option>
            </el-option-group> -->
            <el-option
                    v-for="item in templateOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.name">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="sortable" label="sortable" width="80">
        <template slot-scope="field">
          <el-checkbox v-model="field.row.sortable" true-label=1 false-label=0 ></el-checkbox>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="field">
          <el-button type="danger" icon="el-icon-delete" @click="deleteField(field.row.field)" />
          <el-button type="primary" icon="el-icon-setting" @click="configComponent(field.row)" />
        </template>
      </el-table-column>
    </el-table>
    </template>
    <p>
      <el-button type="primary" @click="initTemplateConfig">初始配置</el-button>
      <el-button type="primary" class="fr" @click="handleConfigSubmit">保存</el-button>
      <el-button type="primary" class="fr" icon="el-icon-plus" @click="addField">新增字段</el-button>
    </p>
    <!----------------------------------- 控件配置 ---------------------------------------------->
    <el-drawer ref="fielddrawer" title="控件配置" :before-close="handleClose" :visible.sync="dialog" direction="rtl" custom-class="demo-drawer" size="60%">
      <div class="demo-drawer_content">
        <el-table :data="tableData" tooltip-effect="dark" style="width: 100%" border>
          <el-table-column prop="key" label="配置项">
            <template slot-scope="field">
              <el-input v-model="field.row.key" placeholder="配置项" autocomplete="off" disabled />
            </template>
          </el-table-column>
         <el-table-column prop="value" label="配置值">
            <template slot-scope="field">
              <el-input v-model="field.row.value" placeholder="配置值" autocomplete="off" clearable />
            </template>
          </el-table-column>
          <el-table-column prop="placeholder" label="配置项说明">
            <template slot-scope="field">
              <el-input v-model="field.row.placeholder" placeholder="" type="textarea" autocomplete="off" disabled />
            </template>
          </el-table-column>
        </el-table>
        <div class="demo-drawer_footer">
          <el-button @click="cancelForm">取 消</el-button>
          <el-button @click="handlePreview">预 览</el-button>
          <el-button type="primary" @click="$refs.fielddrawer.closeDrawer()" :loading="loading">{{ loading ? '提交中 ...' : '确 定' }}</el-button>
        </div>
        <el-input
                type="textarea"
                autosize
                placeholder="生成代码预览"
                :autosize="{ minRows: 10, maxRows: 20}"
                v-model="preview_config">
        </el-input>
      </div>
    </el-drawer>
  </div>


</template>
<script>
  export default {
    name: 'develop_codelabsTemplateConfig',
    props: ['latestCode','templateOptions','templateTag','templateName'],
    data() {
      return {
        url: 'codelabs',
        fields: [],
        types: mysqlTypes,
        inputTypes: inputTypes,
        tableFields: [],
        dialog: false,
        loading: false,
        configComponents: [],
        configRow:[],
        tableData:[],
        timer:null,
        currentComponent:'',
        currentIndex:0,
        preview_config:'',
        component_code:'',
      }
    },
    created() {},
    mounted() {
    },
    methods: {
      deleteField(field) {
        this.fields = this.fields.filter(function(value, key) {
          return value.field !== field
        })
      },
      configComponent(data) {
        console.log('configComponent')
        console.log(data)
        this.currentComponent = data.inputType;
        this.tableData = [];
        this.configRow = data;
        this.currentIndex = this.fields.indexOf(data);
        let submitData = {id:this.latestCode.id,data:data}
        this.$http.post('element/components/initconfig', submitData).then(response => {
          this.configComponents = JSON.parse(response.data);
          for(var row in this.configComponents){
            let elem = {key:this.configComponents[row]['key'],value:this.configComponents[row]['value'],placeholder:this.configComponents[row]['uiSchema']['placeholder']};
            this.tableData.push(elem);
          }
          this.$message.success(response.message)
          this.dialog = true
        })
      },
      getColumn() {
        return {
          'field': '',
          'type': '',
          'length': 0,
          'inputType': '',
          'index': '',
          'default': '',
          'comment': '',
          'sortable': false
        }
      },
    setColumn(arr) {
      return {
        'field': arr['field'],
        'type': arr['type'],
        'length': 0,
        'inputType': arr['inputType'],
        'index': '',
        'default': '',
        'comment': arr['comment'],
        'sortable': false
      }
    },
      setTableColumn(arr) {
        return {
          'field': arr['name'],
          'type': arr['type'],
          'length': 0,
          'inputType': arr['inputType'],
          'index': '',
          'default': '',
          'comment': arr['comment'],
          'sortable': false
        }
      },
      addField() {
        this.fields.push(this.getColumn())
      },
      initTemplateConfig(){
        console.log(this.templateTag);
        this.fields = [];
        if(this.latestCode.data_structure){  //data_structure有内容，以data_structure初始化模板配置
          var dataS = this.latestCode.data_structure;
          var dataSA = JSON.parse(dataS);
          for (const elem of dataSA['table_fields']) {
            this.fields.push(this.setColumn(elem));
          }
        }else if(this.latestCode.data_source){   //以data_source从表结构初始化模板配置
          this.$http.get("table/view/"+ this.latestCode.data_source).then(response => {
            this.tableFields = response.data;
            console.log(this.tableFields)
            let exceptFields = ['id','creator_id','created_at','updated_at','deleted_at'];  //排除模板中无需配置的字段
            for (const elem of this.tableFields) {
              if(!exceptFields.includes(elem['name'])){
                this.fields.push(this.setTableColumn(elem));
              }
            }
          });
        }else{
          let data = {templateTag:this.templateTag,inputType:this.templateName,field:'field'};
          console.log(data)
          this.configComponent(data)
        }
      },
      handleConfigSubmit() {
        let submitData = {id:this.latestCode.id,config_data:JSON.stringify(this.fields)}
        if(this.latestCode.id){
              this.$http.put('codelabs/'+this.latestCode.id, submitData).then(response => {
                this.$message.success(response.message)
              })
        }else{
              this.$http.post('codelabs', submitData).then(response => {
                this.latestCode.id = response.data
                this.$message.success(response.message)
              })
        }
      },
      handleClose(done) {
        if (this.loading) {
          return;
        }
        this.$confirm('确定保存控件配置吗？')
                .then(_ => {
                  this.loading = true;
                  let submitData = {id:this.latestCode.id,config_json:JSON.stringify(this.tableData),configRow:this.configRow}
                  if(this.latestCode.id){
                    this.$http.post('element/components/'+this.currentComponent, submitData).then(response => {
                      this.fields[this.currentIndex].component_code = response.data
                      console.log(this.fields);
                      this.$message.success(response.message)
                    })
                  }
                  this.timer = setTimeout(() => {
                    done();
                    // 动画关闭需要一定的时间
                    setTimeout(() => {
                      this.dialog = false
                      this.loading = false;
                    }, 400);
                  }, 2000);
                })
                .catch(_ => {});
      },
      handlePreview() {
                  let submitData = {id:this.latestCode.id,config_json:JSON.stringify(this.tableData),configRow:this.configRow,preview:1}
                  if(this.latestCode.id){
                    this.$http.post('element/components/'+this.currentComponent, submitData).then(response => {
                      this.preview_config = response.data
                      console.log(this.fields);
                      this.$message.success(response.message)
                    })
                  }

      },
      cancelForm() {
        this.loading = false;
        this.dialog = false;
        clearTimeout(this.timer);
      }
    },
  }
  const mysqlTypes = [
    {
      label: '数字',
      options: [
        { value: 'tinyint' },
        { value: 'smallint' },
        { value: 'mediumint' },
        { value: 'int' },
        { value: 'bigint' },
        { value: 'decimal' },
        { value: 'float' },
        { value: 'uuid' },
        { value: 'boolean' }
      ]
    },
    {
      label: '日期与时间',
      options: [
        { value: 'date' },
        { value: 'datetime' },
        { value: 'timestamp' },
        { value: 'time' }
      ]
    },
    {
      label: '文本',
      options: [
        { value: 'char' },
        { value: 'varchar' },
        { value: 'tinyText' },
        { value: 'text' },
        { value: 'mediumText' },
        { value: 'longText' },
        { value: 'binary' },
        { value: 'varbinary' },
        { value: 'tinyblob' },
        { value: 'blob' },
        { value: 'mediumblob' },
        { value: 'longblob' },
        { value: 'enum' },
        { value: 'set' }
      ]
    },
    /**{
    label: '空间',
    options: [
      { value: 'geometry' },
      { value: 'point' },
      { value: 'linestring' },
      { value: 'polygon' },
      { value: 'multipoint' },
      { value: 'multilinestring' },
      { value: 'multipolygon' },
      { value: 'geometrycollection' }
    ]
  },*/
    {
      label: 'json',
      options: [
        { value: 'json' }
      ]
    }
  ]
  const inputTypes = [
    {
      label: '输入框',
      options: [
        { value: 'input' },
        { value: 'select' },
        { value: 'upload' },
      ]
    },
  /*  {
      label: '日期与时间',
      options: [
        { value: 'date' },
        { value: 'datetime' },
        { value: 'timestamp' },
        { value: 'time' }
      ]
    },
    {
      label: '编辑器',
      options: [
        { value: 'markdown' },
        { value: 'kindeditor' }
      ]
    },
    {
      label: '上传',
      options: [
        { value: 'uploader' }
      ]
    }*/
  ]
</script>
